package com.cms.controller.front;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cms.CommonAttribute;
import com.cms.entity.Cart;
import com.cms.entity.CartItem;
import com.cms.entity.Member;
import com.cms.entity.Order;
import com.cms.entity.OrderItem;
import com.cms.entity.Product;
import com.cms.routes.RouteMapping;
import com.haierubic.bigdata.commons.util.HttpClientUtils;

/**
 * Controller - 购物车
 * 
 * 
 * 
 */
@RouteMapping(url = "/magic")
public class MagicController extends BaseController{

	
	/**
	 * 列表
	 */
	public void add(){
		String url="http://api.12us.com/api/magic/createMagic/";
	    Long magicNum = getParaToLong("magicNum");
	    long unitPrice = getParaToLong("unitPrice");
	    HttpClientUtils.getForJson(url+magicNum+"?praise="+unitPrice, new HashMap<String,String>());
		Cart currentCart = getCurrentCart();
		setAttr("currentCart",currentCart);
		render("/templates/"+getTheme()+"/"+getDevice()+"/magicAdd.html");
	}
	/**
	 * 列表
	 */
//	public void waitinglist(){
//		String url="http://api.12us.com/api/data/query/page/getMagicWaitingList?pageNum=0&pageSize=15";
//	    String page=HttpClientUtils.getForJson(url, new HashMap<String,String>());
//		setAttr("magicWaitings",JSONObject.parseObject(page).getJSONObject("data"));
//		render("/templates/"+getTheme()+"/"+getDevice()+"/waitingMagicList.html");
//	}
	public void waitinglist(){
		String url="http://api.12us.com/api/data/query/page/getMagicWaitingList?pageNum=0&pageSize=15";
	    String page=HttpClientUtils.getForJson(url, new HashMap<String,String>());
	    JSONObject data=JSONObject.parseObject(page).getJSONObject("data");
	    JSONArray rows=new JSONArray();
	    for(Object obj:data.getJSONArray("rows")){
	    	JSONObject json=(JSONObject)obj;
			String urlField="http://api.12us.com/api/data/query/list/getMagicFieldById?drawingRecordId="+json.getString("id");
		    String fieldsJson=HttpClientUtils.getForJson(urlField, new HashMap<String,String>());
	    	json.put("fields", JSONObject.parseObject(fieldsJson).getJSONArray("data"));
	    	rows.add(json);
	    }
	    data.put("rows", rows);
		setAttr("magicWaitings",data);
		render("/templates/"+getTheme()+"/"+getDevice()+"/waitingMagicList.html");
	}
	public void participationMagic(){
		long magicId = getParaToLong("id");
		String url="http://api.12us.com/api/data/query/single/getMagicById?id="+magicId;
		String magicInfo=HttpClientUtils.getForJson(url, new HashMap<String,String>());
		JSONObject magicInfoJson=JSONObject.parseObject(magicInfo).getJSONObject("data");
		String urlField="http://api.12us.com/api/data/query/list/getMagicFieldById?drawingRecordId="+magicId;
		String fieldsJson=HttpClientUtils.getForJson(urlField, new HashMap<String,String>());
		magicInfoJson.put("rows", JSONObject.parseObject(fieldsJson).getJSONArray("data"));
		setAttr("magicWaitingInfo",magicInfoJson);
		render("/templates/"+getTheme()+"/"+getDevice()+"/magicDetail.html");
	}
	
	/**
	 * 保存
	 */
	public void save(){
	    Order order = getModel(Order.class,"",true);
		Member currentMember = getCurrentMember();
		Cart currentCart = getCurrentCart();
		order.setCreateDate(new Date());
		order.setModifyDate(new Date());
		order.setAmount(currentCart.getTotalPrice());
		order.setTotalPrice(currentCart.getTotalPrice());
		order.setQuantity(currentCart.getQuantity());
		order.setSn(DateFormatUtils.format(new Date(), "yyyyMMddHHmmssSSS")+RandomStringUtils.randomNumeric(5));
		order.setStatus(CommonAttribute.ORDER_STATUS_PENDING_PAYMENT);
		order.setMemberId(currentMember.getId());
		order.save();
		List<CartItem>  cartItems = currentCart.getCartItems();
		for(CartItem cartItem:cartItems){
			OrderItem orderItem = new OrderItem();
			orderItem.setCreateDate(new Date());
			orderItem.setModifyDate(new Date());
			orderItem.setName(cartItem.getProduct().getName());
			orderItem.setPrice(cartItem.getPrice());
			orderItem.setQuantity(cartItem.getQuantity());
			orderItem.setSn(cartItem.getProduct().getSn());
			orderItem.setImage(cartItem.getProduct().getImage());
			orderItem.setOrderId(order.getId());
			orderItem.setProductId(cartItem.getProductId());
			orderItem.save();
		}
		for(CartItem cartItem:cartItems){
			new CartItem().dao().deleteById(cartItem.getId());
		}
		redirect("/payment?orderId="+order.getId());
	}
	
	/**
	 * 列表
	 */
	public void list(){
		Cart currentCart = getCurrentCart();
		setAttr("currentCart",currentCart);
		render("/templates/"+getTheme()+"/"+getDevice()+"/cartList.html");
	}
	
	
	/**
	 * 查看
	 */
	public void view(){
	    Cart currentCart = getCurrentCart();
	    Map<String,Object> data = new HashMap<>();
        data.put("quantity", currentCart.getQuantity());
        data.put("totalPrice", currentCart.getTotalPrice());
        List<CartItem> cartItems = currentCart.getCartItems();
        List<Map<String,Object>> cartItemDatas = new ArrayList<>();
        for(CartItem item : cartItems){
            Map<String,Object> cartItemData = new HashMap<>();
            cartItemData.put("quantity", item.getQuantity());
            cartItemData.put("id", item.getId());
            Product product = item.getProduct();
            Map<String,Object> productData = new HashMap<>();
            productData.put("path", product.getPath());
            productData.put("name", product.getName());
            productData.put("image", product.getImage());
            productData.put("price", product.getPrice());
            cartItemData.put("product", productData);
            cartItemDatas.add(cartItemData);
        }
        data.put("cartItems", cartItemDatas);
        renderJson(data);
	}
	
}
